﻿using PinusTools.Enums;
using PinusTools.Models;
using System;
using System.Collections.Generic;
using System.Linq;

namespace PinusTools.DataConverter
{
    public class Package
    {
        public static byte[] Encode(PackageEnum type, byte[] body = null)
        {
            var length = body != null && body.Length > 0 ? body.Length : 0;
            var lengthBytes = BitConverter.GetBytes(length).Reverse();
            var buffer = lengthBytes.ToArray();
            if (body != null && body.Length > 0)
                buffer = buffer.Concat(body).ToArray();
            buffer[0] = (byte)((int)type & 0xff);

            return buffer;
        }

        public static List<PackageDecodeMod> Decode(byte[] buffer)
        {
            var list = new List<PackageDecodeMod>();

            var tempBuffer = buffer.ToList();
            while (tempBuffer.Count > 0)
            {
                var mod = new PackageDecodeMod();
                mod.Type = (PackageEnum)buffer[0];
                tempBuffer.RemoveAt(0);

                var tempLengthByte = new byte[] { 0, tempBuffer[0], tempBuffer[1], tempBuffer[2] }.Reverse().ToArray();
                tempBuffer.RemoveRange(0, 3);
                var length = BitConverter.ToInt32(tempLengthByte, 0);

                if (length > 0)
                {
                    var bodyByte = new byte[length];
                    tempBuffer.CopyTo(0, bodyByte, 0, length);
                    tempBuffer.RemoveRange(0, length);
                    mod.Body = bodyByte;
                }

                list.Add(mod);
            }

            return list;
        }
    }
}